package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BaseBusinessException;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * step2：扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional	// 开启事务
	public boolean handle(TransHandlerContext context) {

		CreateOrderContext createOrderContext = (CreateOrderContext) context;

		List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();

		// 订单中商品id的list
		List<Long> buyProductIds = createOrderContext.getBuyProductIds();

		if(CollectionUtils.isEmpty(buyProductIds)){
			buyProductIds = dtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
		}
		buyProductIds.sort(Long::compareTo);

		// 拿到所有商品的库存信息
		List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);

		if(CollectionUtils.isEmpty(stockList)){
			throw new BizException("库存未初始化！");
		}

		if(stockList.size() != buyProductIds.size()){
			throw new BizException("部分库存未初始化！");
		}

		// 扣减库存
		for (CartProductDto cartProductDto : dtoList) {

			Long productId = cartProductDto.getProductId();
			Long productNum = cartProductDto.getProductNum();

			for (Stock stock : stockList) {
				if(productId.equals(stock.getItemId())){
					// 判断库存是否足够扣除productNum
					if(productNum > stock.getStockCount()){
						throw new BizException(cartProductDto.getProductName() + "的库存不够！");
					}
					// 判断productNum是否超过个人限购数
					if(productNum > stock.getRestrictCount()){
						throw new BizException(cartProductDto.getProductName() + "，购买数量超过个人限买量！");
					}
					break;
				}
			}

			Stock stock = new Stock();
			stock.setItemId(productId);
			stock.setLockCount(productNum.intValue());	// 增加锁定库存
			// 总库存不够的，不会扣减。where item_id = #{itemId} and (stock_count + #{stockCount}) >= 0
			stock.setStockCount(-productNum);	// 扣减总库存

			stockMapper.updateStock(stock);
		}

		return true;
	}
}